# -*- encoding: utf-8 -*-

from Common.mysql import db
from Common.public_method import utc_8
from Common.yaml_method import YamlMethod
from src.ApiTest.SqlData.Database.sql_database import SqlData


class AddSql:
    """
    添加SQL配置
    """

    @staticmethod
    def add_sql(config_name, project_id, project_name, database_type, function_name, sql_data, pre_parameter, after_parameter, create_user):
        """
        添加SQL配置
        :param config_name: 配置名称
        :param project_id: 项目ID
        :param project_name: 项目名称
        :param database_type: 数据库类型
        :param function_name: 运行方法
        :param sql_data: 运行sql
        :param pre_parameter: 前置参数
        :param after_parameter: 数据提取
        :param create_user: 创建人
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        info = SqlData.query.filter_by(configName=config_name, projectId=project_id).first()
        if info is None:
            create_time = utc_8()
            # 项目信息插入数据库
            info = SqlData(configName=config_name, projectId=project_id, projectName=project_name, databaseType=database_type,
                           functionName=function_name, sqlData=sql_data, pre_parameter=pre_parameter,
                           after_parameter=after_parameter, create_time=create_time, create_user=create_user)
            db.session.add(info)
            db.session.commit()

            res = {
                'code': code[0],
                'message': 'success',
                'data': {}
            }
        else:
            res = {
                'code': code[1],
                'message': '配置名称已存在',
                'data': {}
            }
        return res
